<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home/welcome' }"
        >首页</el-breadcrumb-item
      >
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-input
          placeholder="请输入查询关键字"
          clearable
          v-model="query"
          @clear="reloadQuery()"
        ></el-input>
        <el-button icon="el-icon-search" @click="reloadQuery()"></el-button>
        <el-button type="primary" @click="dialogAddUser = true"
          >添加用户</el-button
        >
      </div>
      <div>
        <el-table :data="users" style="width: 100%" border v-loading="loading">
          <el-table-column
            label="序号"
            width="80"
            type="index"
            prop="index"
          ></el-table-column>
          <el-table-column prop="username" label="姓名" width="100">
          </el-table-column>
          <el-table-column prop="email" label="邮箱"> </el-table-column>
          <el-table-column prop="mobile" label="电话"> </el-table-column>
          <el-table-column prop="role_name" label="角色"> </el-table-column>
          <el-table-column prop="mg_state" label="状态">
            <template v-slot:default="{ row }">
              <el-switch v-model="row.mg_state" @change="updateUserState(row)">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" class="el-card-btns">
            <template slot-scope="scope">
              <el-tooltip effect="dark" content="用户编辑" placement="bottom">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="small"
                  @click="modifyUserMsg(scope.row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="删除用户" placement="bottom">
                <el-popconfirm
                  title="是否删除当前用户？删除后不可恢复！"
                  @confirm="removeUser(scope.row.id)"
                >
                  <el-button
                    slot="reference"
                    type="danger"
                    icon="el-icon-delete"
                    size="small"
                  ></el-button>
                </el-popconfirm>
              </el-tooltip>
              <el-tooltip effect="dark" content="分配权限" placement="bottom">
                <el-button
                  type="warning"
                  icon="el-icon-s-tools"
                  size="small"
                  @click="modifyUserRole(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="block">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pagesize"
          :total="total"
          :current-page="pagenum"
          @current-change="reloadUserList"
          @size-change="reloadUserLiseSize"
        >
        </el-pagination>
      </div>

      <el-dialog title="修改用户" :visible.sync="dialogModifyUser">
        <el-form :model="form" :rules="$rules.user" ref="userFormModify">
          <el-form-item label="用户名" :label-width="formLabelWidth">
            <el-input
              v-model="form.username"
              autocomplete="off"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="邮箱" :label-width="formLabelWidth" required>
            <el-input v-model="form.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" :label-width="formLabelWidth" required>
            <el-input v-model="form.mobile"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogModifyUser = false">取 消</el-button>
          <el-button type="primary" @click="modifyUser(form)">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog title="添加新用户" :visible.sync="dialogAddUser">
        <el-form :model="addUserForm" :rules="$rules.user" ref="userFormAdd">
          <el-form-item
            label="用户名"
            :label-width="formLabelWidth"
            prop="username"
            required
          >
            <el-input
              v-model="addUserForm.username"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="密码"
            :label-width="formLabelWidth"
            prop="password"
            required
          >
            <el-input
              v-model="addUserForm.password"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="邮箱"
            :label-width="formLabelWidth"
            prop="email"
            required
          >
            <el-input v-model="addUserForm.email" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item
            label="电话"
            :label-width="formLabelWidth"
            prop="mobile"
            required
          >
            <el-input
              v-model="addUserForm.mobile"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogAddUser = false">取 消</el-button>
          <el-button type="primary" @click="addUser()">确 定</el-button>
        </div>
      </el-dialog>

      <RoleDialog
        :selectUserForm="form"
        :roleVisible.sync="roleVisible"
        @handleModifyRole="handleModifyRole"
      ></RoleDialog>
    </el-card>
  </div>
</template>

<script>
import RoleDialog from "@/components/role/RoleDialog.vue";

export default {
  data() {
    return {
      query: "",
      loading: false,
      total: 0,
      pagenum: 1,
      pagesize: 5,
      users: [],
      data: {},
      dialogAddUser: false,
      addUserForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      dialogModifyUser: false,
      modifyForm: {},
      form: {
        id:0,
        username: "",
        email: "",
        mobile: "",
        role_name: "",
      },
      formLabelWidth: "80px",
      roleVisible: false,
    };
  },
  components: {
    RoleDialog,
  },
  methods: {
    reloadUserList(newPageNum) {
      this.pagenum = newPageNum;
      this.initUsersList();
    },
    reloadUserLiseSize(newPageSize) {
      this.pagesize = newPageSize;
      this.initUsersList();
    },
    reloadQuery() {
      this.pagenum = 1;
      this.initUsersList();
    },
    async initUsersList() {
      try {
        this.loading = true;
        let result = await this.$api.getUserList({
          query: this.query,
          pagenum: this.pagenum,
          pagesize: this.pagesize,
        });
        // console.log(result);
        if (result == "error") return;

        this.total = result.total;
        this.pagenum = result.pagenum;
        this.users = result.users;
      } catch (error) {
        console.log("用户列表加载错误：", error);
      } finally {
        this.loading = false;
      }
    },
    modifyUserMsg(row) {
      this.dialogModifyUser = true;
      this.form.username = row.username;
      this.form.email = row.email;
      this.form.mobile = row.mobile;
      this.modifyForm = row;
    },
    modifyUserRole(row) {
      this.roleVisible = true;
      this.form.id = row.id;
      this.form.username = row.username;
      this.form.role_name = row.role_name;
    },
    handleModifyRole(roleState) {
      //修改角色按钮确定后TODO：

      this.roleVisible = roleState;
    },
    async addUser() {
      try {
        await this.$refs.userFormAdd.validate(); //表单验证

        let result = await this.$api.addNewUser(this.addUserForm);
        console.log("添加用户结果", result);
        if (result == "error") return;
        this.$message.success("用户" + result.username + "添加成功");
        this.dialogAddUser = false;
        this.addUserForm = {
          username: "",
          password: "",
          email: "",
          mobile: "",
        };
        this.initUsersList();
      } catch (error) {
        console.log("用户添加错误：", error);
      }
    },
    async modifyUser(user) {
      try {
        if (
          user.email == this.modifyForm.email &&
          user.mobile == this.modifyForm.mobile
        )
          return;
        let result = await this.$api.updateUserById(this.modifyForm.id, user);
        console.log(result);
        if (result == "error") return;
        this.$message.success("用户修改成功");
        this.dialogModifyUser = false;
        this.initUsersList();
      } catch (error) {
        console.log("用户修改失败：", error);
      }
    },

    async removeUser(id) {
      try {
        let result = await this.$api.removeUserById(id);
        if (result == "error") return;
        this.$message.success("用户删除成功");
        let lastFlag = this.total % this.pagesize == 1;
        let lastPageFlag =
          Math.ceil(this.total / this.pagesize) == this.pagenum;
        if (lastFlag && lastPageFlag && this.pagenum != 1) {
          this.pagenum = this.pagenum - 1;
        }

        this.initUsersList();
      } catch (error) {
        console.log("用户删除错误：", error);
      }
    },
    async updateUserState(user) {
      try {
        let result = await this.$api.updateUserStateByUid(
          user.id,
          user.mg_state
        );
        console.log(result);
        if (result == "error") return;
        this.$message.success("状态修改成功");
      } catch (error) {
        console.log("用户状态修改错误：", error);
      }
    },
  },
  created() {
    this.initUsersList();
  },
};
</script>
<style lang="less" scoped>
.box-card {
  min-width: 950px;

  .clearfix {
    min-width: 560px;
    .el-input {
      width: 300px;
    }
    .el-button {
      width: 100px;
    }
  }
  .el-pagination {
    white-space: nowrap;
    padding: 2px 5px;
    color: #303133;
    font-weight: 700;
    margin-top: 20px;
  }
  .el-select {
    width: 100%;
  }
}
.el-breadcrumb {
  margin-top: 6px;
  margin-bottom: 20px;
}
</style>